<template>
  <HeadContainer class="mine-page-1" :title="$t('title.mine')" disable-back>
    <div v-if="role.avatar" class="d-flex mb-4 mt-4">
      <Avatar
        :src="userData.avatar"
        :radius="35"
        :vip="isVip"
        :vipTier="userData.tier"
        class="me-5"
        :class="{ pointer: isVip }"
        @click="uploadAvatar"
      >
        <template #decorator>
          <div v-if="isVip" class="avatar-camera">
            <div class="outline">
              <Icon name="cameraCenter" size="12"></Icon>
            </div>
          </div>
        </template>
      </Avatar>
      <input
        ref="uploadAvatarInput"
        type="file"
        accept="image/jpg, image/jpeg, image/png, image/gif"
        @change="onImageLoad"
        hidden
      />
      <div class="d-flex flex-column align-start r-content">
        <div class="font-size-16 font-weight-500 mb-05 d-flex align-center gap-row-8 w-100">
          <Icon :name="`vip${userData.tier}`" size="24" v-if="userData.tier<=4&&userData.tier>=1"></Icon>
          <span class="username">{{ userData.nickname }}</span>
          <span v-if="isVip" class="premium">
            <PremiumStar size="20" class="pointer" @click="onPremiumClick"></PremiumStar>
            <span v-show="showPremiumTip" class="tip font-size-10 font-weight-500 line-height-120">{{
              $t('premium.badge.tip')
            }}</span>
          </span>
        </div>
        <div class="font-size-14 mb-4 text-subtitle">@{{ userData.username }}</div>
        <div
          v-if="role.follow"
          @click="navigate(`following`, 2)"
          class="d-flex justify-center align-center font-size-14 pointer"
        >
          <span class="me-1 font-weight-500">{{ userData.follow }}</span>
          <span class="text-subtitle">{{ $t('title.follow') }}</span>
        </div>
      </div>
    </div>
    <div v-if="role.profile" class="d-flex justify-center align-center mb-4 gap-row-24">
      <button
        class="font-size-14 font-weight-500 line-height-140 w-100 primary-btn pointer py-09"
        @click="navigate(`profile`, 2)"
      >
        {{ $t('common.profile') }}
      </button>
      <!-- <button
        v-if="isDev"
        class="font-size-14 font-weight-500 line-height-140 w-100 primary-btn pointer py-09"
        @click="navigate(`fan-send-settings`, 2, fanSendSetTurnOn)"
      >
        {{ $t('title.fanSendSet') }}
      </button> -->
    </div>
    <v-divider v-if="role.follow" class="mb-4"></v-divider>
    <div class="mine-list">
      <div class="gap-col-24">
        <div
          v-if="role.join"
          @click="open(AUTH_ROUTES.SIGN_UP)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="user"></Icon>
            {{ $t('title.join') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div v-if="role.login" @click="open()" class="d-flex justify-space-between w-100 align-center pointer">
          <div class="d-flex align-center">
            <Icon class="me-2" name="login"></Icon>
            {{ $t('title.login') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div
          v-if="role.buyList"
          @click="navigate(`purchases`, 2)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="shop"></Icon>
            {{ $t('title.buyList') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <!-- <div
          v-if="role.buyList"
          @click="navigate(`incomePre`, 2)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="money"></Icon>
            {{ $t('title.enefitsIntroduction') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div> -->
        <div
          v-if="role.earn"
          @click="navigate(`earnings`, 2, turnOn)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="wallet"></Icon>
            {{ $t('title.earn') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div
          v-if="role.premium"
          @click="openPremiumDialog"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="diamond"></Icon>
            {{ $t('title.updatePremium') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div v-if="role.buyList" @click="toFavorite" class="d-flex justify-space-between w-100 align-center pointer">
          <div class="d-flex align-center">
            <Icon class="me-2" name="heartOutline"></Icon>
            {{ $t('title.collectFavorite') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div
          v-if="role.media"
          @click="navigate(`media`, 2)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="media"></Icon>
            {{ $t('title.media') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <Link v-if="role.settings" href="/mine/settings" @click="navigate(`settings`, 2)">
          <div class="d-flex justify-space-between w-100 align-center pointer">
            <div class="d-flex align-center">
              <Icon class="me-2" name="setting"></Icon>
              {{ $t('title.setting') }}
              <div v-if="setAlertCount" class="tag ml-2 bg-primary font-size-10 font-weight-500 line-height-120">
                {{ setAlertCount }}
              </div>
            </div>
            <Icon class="ms-2" name="arrowRight"></Icon>
          </div>
        </Link>
        <Link v-if="role.help" href="/mine/faq" @click="navigate(`faq`, 2)">
          <div class="d-flex justify-space-between w-100 align-center pointer">
            <div class="d-flex align-center">
              <Icon class="me-2" name="ask"></Icon>
              {{ $t('title.help') }}
            </div>
            <Icon class="ms-2" name="arrowRight"></Icon>
          </div>
        </Link>
        <Link v-if="role.beCreator" href="/mine/creator-faq" @click="navigate(`creator-faq`, 2)">
          <div class="d-flex justify-space-between w-100 align-center pointer">
            <div class="d-flex align-center">
              <Icon class="me-2" name="crown"></Icon>
              <!-- {{ $t('title.beCreator') }} -->
              {{ $t('title.creatorFAQ') }}
            </div>
            <Icon class="ms-2" name="arrowRight"></Icon>
          </div>
        </Link>
        <div
          v-if="role.prefer"
          @click="navigate(`gender-visitor`, 2)"
          class="d-flex justify-space-between w-100 align-center pointer"
        >
          <div class="d-flex align-center">
            <Icon class="me-2" name="filter"></Icon>
            {{ $t('title.prefer') }}
          </div>
          <div>
            <Icon class="ms-2" name="arrowRight"></Icon>
          </div>
        </div>
        <div v-if="role.language" @click="toggleLangOptions" class="custom-select">
          <div class="d-flex align-center justify-space-between">
            <div class="d-flex align-center">
              <Icon class="me-2" name="language"></Icon>
              {{ $t('title.language') }}
            </div>
            <div class="d-flex align-center">
              <span>{{ $t(`lang.${getLocaleTrans(locale)}`) }}</span>
              <Icon class="ms-2" name="arrowRight"></Icon>
            </div>
          </div>
          <transition name="fade">
            <div v-show="showOptions" class="options">
              <div
                v-for="(locale, index) in locales"
                :key="`locale-${index}-${locale.value}`"
                @click="selectLangOption(locale.value)"
                class="option"
              >
                <span class="font-size-12 font-weight-500 line-height-120">{{ $t(`lang.${locale.label}`) }}</span>
                <Icon v-if="isSelected(locale.value)" class="me-1 icon-size-12" name="check"></Icon>
              </div>
            </div>
          </transition>
        </div>
        <Link v-if="role.legal" href="/mine/legal" @click="navigate(`legal`, 2)">
          <div class="d-flex justify-space-between w-100 align-center pointer">
            <div class="d-flex align-center">
              <Icon class="me-2" name="info"></Icon>
              {{ $t('title.legal') }}
            </div>
            <Icon class="ms-2" name="arrowRight"></Icon>
          </div>
        </Link>
        <div v-if="role.feedback" @click="feedback()" class="d-flex justify-space-between w-100 align-center pointer">
          <div class="d-flex align-center">
            <Icon class="me-2" name="feedback"></Icon>
            {{ $t('title.feedback') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div v-if="role.logout" @click="logout()" class="d-flex justify-space-between w-100 align-center pointer">
          <div class="d-flex align-center">
            <Icon class="me-2" name="mine"></Icon>
            {{ $t('title.logout') }}
          </div>
          <Icon class="ms-2" name="arrowRight"></Icon>
        </div>
        <div v-if="!isPwaApp" class="d-flex justify-space-between w-100 align-center pointer">
          <div class="d-flex align-center">
            <Icon class="me-2" name="download"></Icon>
            {{ $t('title.installFantasi') }}
          </div>
          <button
            class="primary-btn primary-gradient download-btn font-size-14 font-weight-500 line-height-140"
            @click="onInstallClick"
          >
            {{ $t('common.install') }}
          </button>
        </div>
        <div class="gap-col-24 mt-4 about-list">
          <div class="d-flex justify-space-between w-100 align-center">
            <div class="d-flex align-center">
              <Icon class="me-2" name="version"></Icon>
              {{ `${$t('title.version')} ${version}` }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </HeadContainer>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAdDialogStore } from '@/store/ad-dialog'
import { useAppStore } from '@/store/app'
import { useAuthDialogStore } from '@/store/auth-dialog'
import { useEarnStore } from '@/store/earn'
import { useInstallTutorStore } from '@/store/install-tutor'
import { useNavStore } from '@/store/nav'
import { usePermissionStore } from '@/store/permission.js'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t, locale, locales, setLocale } from '@/i18n'
import Link from '@/components/common/Link.vue'
import PremiumStar from '@/components/common/PremiumStar.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import Avatar from '@/components/multimedia/Avatar.vue'
import useCutImage from '@/compositions/dialog/cut-image'
import { useDialog } from '@/compositions/viewer/dialog'
import { AUTH_ROUTES, PERMISSION, POPUP_AD_DIALOG, POPUP_DIALOG_TYPE } from '@/constant'
import { TAB_TYPE } from '@/constant/search'
import { trackEvent } from '@/gtm'

const { $openAdDialog } = useAdDialogStore()

function openPremiumDialog() {
  $openAdDialog(POPUP_AD_DIALOG.PREMIUM).open()
}

const version = import.meta.env.VITE_APP_VERSION
const isDev = import.meta.env.DEV

// store 應用
const { open: $openPopupMessage } = usePopupMessageStore()
const { feedback } = useDialog()

const appStore = useAppStore()
const { isMobile, isPwaApp } = storeToRefs(appStore)

const { open: $openInstallTutorial } = useInstallTutorStore()

function openInstallTutorial() {
  $openInstallTutorial()
  trackEvent({ key: 56 })
}

const { $popupDialog } = usePopupDialogStore()

function openInstallQrcode() {
  $popupDialog(POPUP_DIALOG_TYPE.INSTALL_QRCODE, {
    title: $t('title.installFantasi'),
    showConfirm: false,
  }).open()
}

const onInstallClick = isMobile.value ? openInstallTutorial : openInstallQrcode

const accountStore = useAccountStore()
const { userData, isLogin, isVip } = storeToRefs(accountStore)

const navStore = useNavStore()
const { toSearch } = navStore
const { searchTab } = storeToRefs(navStore)
const toFavorite = () => (searchTab.value === TAB_TYPE.FAVORITE ? toSearch() : (searchTab.value = TAB_TYPE.FAVORITE))

const router = useRouter()

const permissionStore = usePermissionStore()
const { role } = storeToRefs(permissionStore)

// 角色權限顯示
watch(
  [isLogin, () => userData.value.is_creator],
  ([isLoginValue, isCreator]) => {
    if (!isLoginValue) {
      role.value = PERMISSION.VISITOR
      console.log(`watch裡面 isLoginValue為${isLoginValue}, 你是遊客`)
    } else if (isCreator) {
      role.value = PERMISSION.CREATOR
      console.log(`watch裡面 isCreator為${isCreator}, 你是創作者`)
    } else {
      role.value = PERMISSION.REGISTERED
      console.log('如果看到這個的話，你是註冊會員齁')
    }
  },
  { immediate: true },
)

// 註冊 & 登入
const authDialogStore = useAuthDialogStore()
const { open } = authDialogStore

// 登出
const { $confirm } = usePopupDialogStore()
const { logout: logoutAccount } = useAccountStore()
const logout = () => {
  $confirm({
    title: $t('title.logout'),
    content: $t('content.logout'),
    confirm: logoutAccount,
    cancel: () => {},
  }).open()
}

// 是否顯示粉絲訊息設定，用於觸發該頁的API
const fanSendSetStore = useEarnStore()
const { fanSendSetTurnOn } = fanSendSetStore

// 是否顯示收益頁面，用於觸發收益頁面的API
const earnStore = useEarnStore()
const { turnOn } = earnStore

// 到達其他頁面
const emits = defineEmits(['toPage'])

function navigate(to, page, fn = null) {
  if (fn) fn()
  emits('toPage', page, to)
  switch (to) {
    case 'faq':
    case 'creator-faq':
    case 'settings':
    case 'legal':
      router.replace({ name: 'mine', params: { to }, hash: window.location.hash })
      break
  }
}

// 語言下拉式選單
const showOptions = ref(false)

const toggleLangOptions = () => {
  showOptions.value = !showOptions.value
}

const selectLangOption = async (option) => {
  try {
    await setLocale(option)
    $openPopupMessage($t('info.setLanguageSucceed'))
  } catch (e) {
    console.error(e)
  }
}

const isSelected = (option) => {
  return option === locale.value
}

window.addEventListener('click', (event) => {
  const customSelect = document.querySelector('.custom-select')
  if (customSelect && !customSelect.contains(event.target)) {
    showOptions.value = false
  }
})

const getLocaleTrans = (localeCode) => {
  if (localeCode === 'zh-tw' || localeCode === 'zh-cn') {
    return localeCode.replace('-', '_')
  }
  return localeCode
}

const setAlertCount = computed(() => {
  return userData.value.is_bind_email ? '' : '1'
})

const showPremiumTip = ref(false)

function onPremiumClick() {
  clearTimeout(onPremiumClick.timerId)
  showPremiumTip.value = true
  onPremiumClick.timerId = setTimeout(() => (showPremiumTip.value = false), 5000)
}

const uploadAvatarInput = ref(null)
const uploadAvatar = () => (isVip.value ? uploadAvatarInput.value.click() : void 0)
const { onImageLoad } = useCutImage({ inputRef: uploadAvatarInput })
</script>

<style lang="scss" scoped>
.mine-page-1 {
  width: 100%;
  height: 100%;
}

.mb-05 {
  margin-bottom: 0.125rem;
}

.primary-gradient {
  padding: 0.6525rem;
}

.primary-btn {
  padding: 0.5625rem 1rem;
}

.premium {
  position: relative;

  .tip {
    width: 6rem;
    padding: 0.25rem 1rem;
    border-radius: 0.75rem 0.125rem 0.75rem 0.75rem;
    background: linear-gradient(180deg, rgba(249, 94, 14, 0.75) -40%, rgba(231, 23, 179, 0.75) 112.5%);
    position: absolute;
    top: 100%;
    right: 0.5rem;
  }
}

.custom-select {
  position: relative;
  cursor: pointer;
}

.selected-option {
  display: flex;
  align-items: center;
  padding: 0.625rem;
  border-radius: 0.3125rem;
}

.options {
  max-height: 9rem;
  width: 8rem;
  margin-bottom: 0.5rem;
  background: rgba(var(--v-theme-background), 0.75);
  border: 1px solid rgba(var(--v-theme-input), 0.6);
  border-radius: 0.3125rem;
  box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
  color: white;
  position: absolute;
  right: 0;
  bottom: 100%;
  z-index: 1;
  overflow: auto;

  &::-webkit-scrollbar {
    display: flex;
    width: 0.25rem;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(var(--v-theme-graydisabled), 0.4);
    background-clip: content-box;
    border-radius: 0.25rem;
  }
}

.option {
  padding: 0.5rem 0.5rem 0.5rem 1rem;
  transition: background-color 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option:hover {
  background-color: rgba(var(--v-theme-gray-x), 0.5);
  color: white;
}

.download-btn {
  min-height: 1.5rem;
  padding: 0.125rem 1rem;
  background: linear-gradient(180deg, #f95e0e -40%, #e717b3 112.5%);
}

.tag {
  width: 1rem;
  height: 1rem;
  border-radius: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
}

.avatar-camera {
  position: absolute;
  bottom: 0;
  right: 0;

  .outline {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 1.125rem;
    height: 1.125rem;
    border-radius: 50%;
    background-color: rgb(var(--v-theme-background));
    box-shadow: 0 0 0 0.0625rem #ffffff;
  }
}
.r-content{
  width: calc(100% - 6rem);
  .username{
    height: 100%;
    line-height: 1.5rem;
    overflow-x:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow:ellipsis;
  }
}

</style>
